﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace TCL.FUNC
{
    public class StringEx
    {
        /// <summary>
        /// Trim Extend (remove: double space, double-header space, break line, null to empty)
        /// </summary>
        /// <param name="sInput">  jdk   empty </param>
        /// <returns>jdk empty</returns>
        public static String TrimEx(String sInput)
        {
            if (sInput != null && (!string.IsNullOrEmpty(sInput)))
            {
                sInput = System.Text.RegularExpressions.Regex.Replace(sInput, @"\s+", " ").Trim();
                sInput = sInput.Replace(Environment.NewLine, "");
                return sInput.Trim();
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// Trim Extend (remove: double-header space, break line, null to empty)
        /// </summary>
        /// <param name="sInput">  jdk   empty </param>
        /// <returns>jdk   empty</returns>
        public static String Trim(String sInput)
        {
            if (sInput != null && (!string.IsNullOrEmpty(sInput)))
            {
                sInput = sInput.Replace(Environment.NewLine, "");
                return sInput.Trim();
            }
            else
            {
                return "";
            }
        }

        public static String Trim(String sInput, String DefaultIsNull)
        {
            sInput = Trim(sInput);
            if (String.IsNullOrEmpty(sInput))
                return DefaultIsNull;
            else
                return sInput;
        }

        public static String Remove_Protocol_From_Url(String sInput)
        {
            sInput = Trim(sInput);
            System.Uri uri = new Uri(sInput);
            return uri.Host + uri.PathAndQuery;
        }

        public static String Get_Query_String_From_Url(String sUrl, String query)
        {
            sUrl = Trim(sUrl);
            System.Uri uri = new Uri(sUrl);
            return Trim(System.Web.HttpUtility.ParseQueryString(uri.Query).Get(query));
        }

        public static Boolean Equals(String strSrc, String strDes)
        {
            strSrc = Convert.ToString(getDefaultValue(strSrc, ""));
            strDes = Convert.ToString(getDefaultValue(strDes, ""));
            string temp;
            if (strSrc.Length < strDes.Length)
            {
                temp = strSrc;
                strSrc = strDes;
                strDes = temp;
            }
            return Trim(strSrc).ToLower().Equals(Trim(strDes).ToLower());
        }

        public static Object getDefaultValue(Object objField, Object DefaultValue)
        {
            if (objField is DBNull || objField == null)
                return DefaultValue;
            else
                return objField;
        }

        /// <summary>
        /// Reverse - Hàm đảo ngược 1 chuỗi string
        /// </summary>
        /// <param name="sInput">ThangNM</param>
        /// <returns>MNgnahT</returns>
        public static String Reverse(String sInput)
        {
            char[] arr = sInput.ToCharArray();
            Array.Reverse(arr);
            return new string(arr);
        }


        /// <summary>
        /// SplitByLength Cắt nhỏ chuỗi ra thành 1 list<string> theo 1 độ dài quy định
        /// </summary>
        /// <param name="str"></param>
        /// <param name="maxLength"></param>
        /// <returns></returns>
        public static List<String> SplitByLength(String sInput, Int32 maxLength)
        {
            List<string> a = new List<string>();
            for (int i = 0; i < sInput.Length; i += maxLength)
            {
                if ((i + 3) < sInput.Length)
                    a.Add(sInput.Substring(i, 3));
                else
                    a.Add(sInput.Substring(i));
            }
            return a;
        }

        /// <summary>
        /// SplitByLengthEnum Cắt nhỏ chuỗi ra thành 1 Enum theo 1 độ dài quy định
        /// </summary>
        /// <param name="sInput"></param>
        /// <param name="maxLength"></param>
        /// <returns></returns>
        public static IEnumerable<String> SplitByLengthEnum(String sInput, Int32 maxLength)
        {
            for (int index = 0; index < sInput.Length; index += maxLength)
            {
                yield return sInput.Substring(index, Math.Min(maxLength, sInput.Length - index));
            }
        }

        public static String Split_sFB_ID(String sInput, Int16 iIndex, Char cSeparator = '_')
        {
            String sRet = "";
            sInput = StringEx.Trim(sInput);
            String[] arrTemp = sInput.Split(cSeparator);
            if (arrTemp.Length > iIndex)
                sRet = StringEx.Trim(arrTemp[iIndex]);
            return sRet;
        }

        public static Int64 Split_iFB_ID(String sInput, Int16 iIndex, Char cSeparator = '_')
        {
            Int64 iRet = 0;
            sInput = StringEx.Trim(sInput);
            String[] arrTemp = sInput.Split(cSeparator);
            if (arrTemp.Length > iIndex)
                Int64.TryParse(StringEx.Trim(arrTemp[iIndex]), out iRet);
            return iRet;
        }

        public static String UppercaseFirst(String sInput)
        {
            if (string.IsNullOrEmpty(sInput))
            {
                return string.Empty;
            }
            return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(sInput.ToLower());
        }

        public static Boolean Compare(String strSrc, String strDes)
        {
            strSrc = Convert.ToString(getDefaultValue(strSrc, ""));
            strDes = Convert.ToString(getDefaultValue(strDes, ""));
            string temp;
            if (strSrc.Length < strDes.Length)
            {
                temp = strSrc;
                strSrc = strDes;
                strDes = temp;
            }
            return strSrc.ToLower().Contains(strDes.ToLower());
        }

        public static Boolean CompareEx(String strSrc, String strDes)
        {
            strSrc = Convert.ToString(getDefaultValue(strSrc, ""));
            strDes = Convert.ToString(getDefaultValue(strDes, ""));
            strSrc = Remove_Unicode_Character(strSrc);
            strDes = Remove_Unicode_Character(strDes);
            return Compare(strSrc, strDes);
        }

        public static List<String> Split(String sInput, Char ch)
        {
            List<String> temp;
            temp = Trim(sInput).Split(ch).ToList();
            temp.RemoveAll(x => String.IsNullOrEmpty(x));
            return temp;
        }

        public static String remove_dublicate_in_string_array(String sInput)
        {
            sInput = StringEx.Trim(sInput);
            string[] arr = sInput.Split(',');
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = StringEx.TrimEx(arr[i]);
                if (Equals(arr[i], "") || Equals(arr[i], ""))
                {
                }
            }
            sInput = "," + String.Join(",", arr.Distinct().ToArray()) + ",";
            return System.Text.RegularExpressions.Regex.Replace(sInput, @",+", ",").Trim();
        }

        public static String getDefaultArrayInDB(String sInput)
        {
            sInput = StringEx.Trim(sInput);
            if (String.IsNullOrEmpty(sInput))
                return ",";
            else
                return sInput;
        }

        public static String Remove_Unicode_Character(String sInput)
        {
            Regex regex = new Regex(@"\p{IsCombiningDiacriticalMarks}+");
            string strFormD = sInput.Normalize(System.Text.NormalizationForm.FormD);
            return regex.Replace(strFormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
        }

        public static Int32 RemoveKB(Object drField)
        {
            return Convert.ToInt32(StringEx.Trim(drField.ToString().Replace("KB", "")));
        }

        public static String getArrayKey(String arrKey)
        {
            arrKey = Convert.ToString(arrKey);
            List<String> lstTemp = arrKey.Split(',').ToList();
            lstTemp.RemoveAll(str => String.IsNullOrEmpty(str));
            return String.Join(",", lstTemp.ToArray());
        }

        public static String RemoveHtmlTagsUsingCharArray(String sInput)
        {
            sInput = StringEx.Trim(sInput);
            string strOutput = "";
            var array = new Char[sInput.Length];
            var arrayIndex = 0;
            var inside = false;

            foreach (var @let in sInput)
            {
                if (let == '<')
                {
                    inside = true;
                    continue;
                }
                if (let == '>')
                {
                    inside = false;
                    continue;
                }
                if (inside) continue;
                array[arrayIndex] = let;
                arrayIndex++;
            }
            strOutput = new String(array, 0, arrayIndex);
            strOutput = strOutput.Replace("&nbsp;", " ");
            strOutput = strOutput.Replace(Environment.NewLine, " ");
            strOutput = System.Text.RegularExpressions.Regex.Replace(strOutput, @"\s+", " ").Trim(); // convert multiple spaces into one space  
            strOutput = strOutput.Replace("\n", "");
            strOutput = strOutput.Replace("\t", "");
            return strOutput;
        }

        public static String ConvertToUnSign_Other(String sInput)
        {
            for (int i = 32; i < 48; i++)
            {
                if (i != 46)
                {
                    sInput = sInput.Replace(((Char)i).ToString(), " ");
                }
            }
            //text = text.Replace(".", "-");
            sInput = sInput.Replace(" ", "-");
            sInput = sInput.Replace(",", "-");
            sInput = sInput.Replace(";", "-");
            sInput = sInput.Replace(":", "-");
            Regex regex = new Regex(@"\p{IsCombiningDiacriticalMarks}+");
            String strFormD = sInput.Normalize(System.Text.NormalizationForm.FormD);
            return regex.Replace(strFormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
        }

        /// <summary> RemoveHtmlTags (Loại bỏ thẻ html) </summary>
        /// <param name="sInput"></param>
        /// <returns></returns>
        public static String RemoveHtmlTags(String sInput)
        {
            var array = new Char[sInput.Length];
            var arrayIndex = 0;
            var inside = false;

            foreach (var @let in sInput)
            {
                if (let == '<')
                {
                    inside = true;
                    continue;
                }
                if (let == '>')
                {
                    inside = false;
                    continue;
                }
                if (inside) continue;
                array[arrayIndex] = let;
                arrayIndex++;
            }
            return new String(array, 0, arrayIndex);
        }

        public static String GetRawUrlQueryString(String url, String page1, Int32 page2)
        {
            string sUrl = "";
            if (string.IsNullOrEmpty(page1))
            {
                sUrl = url + ConstEx.UrlEX_C._Trang + page2;
            }
            else
            {
                sUrl = url.Replace(ConstEx.UrlEX_C.Trang + page1, ConstEx.UrlEX_C.Trang + page2);
            }
            return sUrl;
        }

        public static String ConvertToUnSign(String sInput)
        {
            if (!String.IsNullOrEmpty(sInput))
            {
                string str = StringEx.Remove_Unicode_Character(sInput).ToLower();
                //str = System.Text.RegularExpressions.Regex.Replace(str, @"[-_+.,/\|]", " "); // //Replace "-", "_", "+", ".", "," by space
                str = System.Text.RegularExpressions.Regex.Replace(str, @"[^a-z0-9\s]", " "); // Remove all non valid chars          
                str = System.Text.RegularExpressions.Regex.Replace(str, @"\s+", " ").Trim(); // convert multiple spaces into one space
                str = System.Text.RegularExpressions.Regex.Replace(str, @"\s", "-"); // //Replace spaces by dashes
                return str;
            }
            else
                return "";
        }

        /// <summary>
        /// Đánh dấu từ khóa với thuộc tính background-color
        /// </summary>
        /// <param name="sInput"></param>
        /// <param name="keywords">Từ khóa tìm kiếm</param>
        /// <param name="cssClass">Css style hoặc color đánh dấu từ khóa</param>
        /// <returns>string</returns>
        public static String HighLightKeyWords(String sInput, String keywords, String cssClass)
        {
            if (sInput == String.Empty || keywords == String.Empty || cssClass == String.Empty)
                return sInput;
            var words = keywords.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            return words.Select(
                word => word.Trim()).Aggregate(sInput, (current, pattern) =>
                Regex.Replace(current, pattern, string.Format("<span style=\"color:{0}; font-weight: bold\">{1}</span>", cssClass, "$0"), RegexOptions.IgnoreCase));
            return words.Select(word => "\\b" + word.Trim() + "\\b").Aggregate(sInput, (current, pattern) => Regex.Replace(current, pattern, string.Format("<span style=\"background-color:{0}\">{1}</span>", cssClass, "$0"), RegexOptions.IgnoreCase));
        }

        public static String Remove_Special_Character_SQLite(String sInput)
        {
            return TrimEx(sInput).Replace("'", "\"");
        }

        public static String getFirtChar_AllWord_InParagraph(String sInput)
        {
            sInput = Trim(sInput);
            if (String.IsNullOrEmpty(sInput))
                return "";
            List<String> lstWord = sInput.Split(' ').ToList();
            sInput = "";
            foreach (var item in lstWord)
            {
                if (!String.IsNullOrEmpty(item))
                    sInput += (item.Substring(0, 1)).ToLower();
            }
            return sInput;
        }
    }
}
